# views.py
import csv

from django.shortcuts import render, redirect, get_object_or_404
from django.http import JsonResponse, HttpResponse
from .models import Good
from django.views.decorators.csrf import csrf_exempt


# 商品列表视图
@csrf_exempt
def good_list(request):
    goods = Good.objects.all()
    return render(request, 'good-list.html', {'goods': goods})


# 添加商品视图
@csrf_exempt
def good_add(request):
    if request.method == 'POST':
        Gid = request.POST.get('Gid')
        GName = request.POST.get('GName')
        GPay = request.POST.get('GPay')
        Cid = request.POST.get('Cid')
        GIntroduction = request.POST.get('GIntroduction')
        other = request.POST.get('other')

        Good.objects.create(
            Gid=Gid,
            GName=GName,
            GPay=GPay,
            Cid=Cid,
            GIntroduction=GIntroduction,
            other=other
        )
        return JsonResponse({'code': '200', 'message': '添加成功'})
    return render(request, 'good-add.html')


# 根据ID查找商品视图
def good_find_by_id(request):
    Gid = request.GET.get('id')
    good = get_object_or_404(Good, Gid=Gid)
    return render(request, 'good-update.html', {'good': good})


# 修改商品视图
@csrf_exempt
def good_update(request):
    if request.method == 'POST':
        Gid = request.POST.get('Gid')
        good = get_object_or_404(Good, Gid=Gid)
        good.GName = request.POST.get('GName')
        good.GPay = request.POST.get('GPay')
        good.Cid = request.POST.get('Cid')
        good.GIntroduction = request.POST.get('GIntroduction')
        good.other = request.POST.get('other')
        good.save()
        return JsonResponse({'code': 200, 'message': '商品信息更新成功'})
    else:
        return JsonResponse({'code': 400, 'message': '请求方法错误'})


# 删除商品视图
@csrf_exempt
def good_delete(request, good_id):
    try:
        good = Good.objects.get(Gid=good_id)
        good.delete()
        return JsonResponse({'code': 200, 'message': '删除成功'})
    except Good.DoesNotExist:
        return JsonResponse({'code': 404, 'message': '商品不存在'})


def export_goods_csv(request):
    response = HttpResponse(content_type='text/csv; charset=utf-8')
    response['Content-Disposition'] = 'attachment; filename="goods.csv"'

    # 商品数据的字段名，中文表头
    field_names = ['商品编号', '商品名称', '商品单价', '客户编号', '商品简介', '备注']

    # 写入 CSV 文件
    writer = csv.writer(response, delimiter=';', quotechar='"', quoting=csv.QUOTE_MINIMAL)
    writer.writerow([name for name in field_names])  # 写入表头

    # 获取所有商品数据
    goods = Good.objects.all()

    # 将商品数据写入 CSV 文件
    for good in goods:
        writer.writerow([
            good.Gid,
            good.GName,
            good.GPay,
            good.Cid,
            good.GIntroduction,
            good.other,
        ])

    # 设置 UTF-8 with BOM 编码格式
    response.write('\ufeff'.encode('utf-8'))

    return response
